package myky.com.doctorapp.utils;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

/**
 * Created by 61904 on 2017/1/12.
 */


//做本地缓存数据库管理工具类
public class DBManager {
    private static SQLiteDatabase db;
    private static MySQLiteCache dbHelper;

    public DBManager(Context context) {

    }

    /**
     * 插入缓存，没有就插入，有就替换
     *
     * @param url  地址
     * @param data json数据
     */
    public static synchronized void insertData(String url, String data, Context context) {

        dbHelper = new MySQLiteCache(context);
        db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(MySQLiteCache.URL, url);
        values.put(MySQLiteCache.DATA, data);
        values.put(MySQLiteCache.TIME, System.currentTimeMillis());
        db.replace(MySQLiteCache.CACHE, null, values);
        db.close();
    }

    /**
     * 根据url获取缓存数据
     *
     * @param url 地址
     * @return 数据
     */
    public static synchronized String getData(String url, Context context) {
        dbHelper = new MySQLiteCache(context);
        String result = "";
        db = dbHelper.getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT * FROM " + MySQLiteCache.CACHE + " WHERE URL = ?", new String[]{url});
        while (cursor.moveToNext()) {
            result = cursor.getString(cursor.getColumnIndex(MySQLiteCache.DATA));
        }
        cursor.close();
        db.close();
        return result;
    }

}
